﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BBCodeParser.Tags;

namespace BBCodeParser.Nodes
{
	public class TagNode : Node
	{
		public string AttributeValue { get; private set; }
		public Tag Tag { get; private set; }

		public TagNode(Tag tag, Node parent, string attributeValue)
		{
			Tag = tag;
			AttributeValue = attributeValue;
			ChildNodes = new List<Node>();
			ParentNode = parent;
		}

		internal override string ToHtml(Dictionary<string, string> substitutions, Func<Node, bool> filter = null)
		{
			var result = new StringBuilder(Tag.GetOpenHtml(AttributeValue), ChildNodes.Count + 2);
			foreach (var childNode in ChildNodes.Where(n => filter == null || filter(n)))
			{
				if (Tag is CodeTag)
				{
					result.Append(childNode.ToBb(substitutions));
				}
				else
				{
					result.Append(childNode.ToHtml(substitutions, filter));
				}
			}
			if (Tag.RequiresClosing)
			{
				result.Append(Tag.GetCloseHtml(AttributeValue));
			}
			return result.ToString();
		}

	    internal override string ToText(Dictionary<string, string> substitutions)
	    {
	        var result = new StringBuilder(ChildNodes.Count);
	        foreach (var childNode in ChildNodes)
			{
				if (Tag is CodeTag)
				{
					result.Append(childNode.ToBb(substitutions));
				}
				else
				{
					result.Append(childNode.ToText(substitutions));
				}
	        }
	        return result.ToString();
	    }

	    public override string ToBb(Dictionary<string, string> substitutions = null)
		{
			var result = new StringBuilder(Tag.WithAttribute
				? string.Format(@"[{0}=""{1}""]", Tag.Name, AttributeValue)
				: string.Format(@"[{0}]", Tag.Name), ChildNodes.Count + 2);
			foreach (var childNode in ChildNodes)
			{
				result.Append(childNode.ToBb(substitutions));
			}
			if (Tag.RequiresClosing)
			{
				result.Append(string.Format(@"[/{0}]", Tag.Name));
			}
			return result.ToString();
		}
	}
}